package com.sxt.demo.djiapplication.dji;

import android.app.Application;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.sxt.demo.djiapplication.utils.ToastUtils;

import dji.common.error.DJIError;
import dji.common.error.DJISDKError;
import dji.sdk.base.BaseComponent;
import dji.sdk.base.BaseProduct;
import dji.sdk.camera.Camera;
import dji.sdk.products.Aircraft;
import dji.sdk.products.HandHeld;
import dji.sdk.sdkmanager.DJISDKInitEvent;
import dji.sdk.sdkmanager.DJISDKManager;

@SuppressWarnings("unused")
public class DJIDemoContext {

    public static final String FLAG_CONNECTION_CHANGE = "fpv_tutorial_connection_change";

    private static BaseProduct mProduct;

    public Handler mHandler;

    private final Application application;

    public DJIDemoContext(Application application) {
        this.application = application;
    }

    /**
     * This function is used to get the instance of DJIBaseProduct.
     * If no product is connected, it returns null.
     */
    public static synchronized BaseProduct getProductInstance() {
        if (null == mProduct) {
            mProduct = DJISDKManager.getInstance().getProduct();
        }
        return mProduct;
    }

    /**
     * 获取相机实例
     *
     * @return {@link Camera}
     */
    public static synchronized Camera getCameraInstance() {
        if (getProductInstance() == null) return null;
        Camera camera = null;
        if (getProductInstance() instanceof Aircraft) {
            camera = ((Aircraft) getProductInstance()).getCamera();
        } else if (getProductInstance() instanceof HandHeld) {
            camera = ((HandHeld) getProductInstance()).getCamera();
        }
        return camera;
    }

    public void onCreate() {
        mHandler = new Handler(Looper.getMainLooper());

        /*
          When starting SDK services, an instance of interface DJISDKManager.DJISDKManagerCallback will be used to listen to
          the SDK Registration result and the product changing.
         */
        //Listens to the SDK registration result
        DJISDKManager.SDKManagerCallback mDJISDKManagerCallback = new DJISDKManager.SDKManagerCallback() {

            //Listens to the SDK registration result
            @Override
            public void onRegister(DJIError djiError) {
                Handler handler = new Handler(Looper.getMainLooper());
                if (djiError == DJISDKError.REGISTRATION_SUCCESS) {
                    handler.post(() -> Toast.makeText(application.getApplicationContext(), "Register Success", Toast.LENGTH_LONG).show());
                    DJISDKManager.getInstance().startConnectionToProduct();
                } else {

                    handler.post(() -> Toast.makeText(application.getApplicationContext(), "Register sdk fails, check network is available", Toast.LENGTH_LONG).show());

                }
                Log.e("TAG", djiError.toString());
            }

            @Override
            public void onProductDisconnect() {
                ToastUtils.show("产品连接已断开");
                Log.d("TAG", "onProductDisconnect");
                notifyStatusChange();
            }

            @Override
            public void onProductConnect(BaseProduct baseProduct) {
                ToastUtils.show("检测到产品连接, 电量: " + baseProduct.getBattery().getNumberOfCells() + "%");
                Log.d("TAG", String.format("onProductConnect newProduct:%s", baseProduct));
                notifyStatusChange();
            }

            @Override
            public void onProductChanged(BaseProduct baseProduct) {
                notifyStatusChange();
            }

            @Override
            public void onComponentChange(BaseProduct.ComponentKey componentKey, BaseComponent oldComponent,
                                          BaseComponent newComponent) {
                if (newComponent != null) {
                    newComponent.setComponentListener(isConnected -> {
                        Log.d("TAG", "onComponentConnectivityChanged: " + isConnected);
                        notifyStatusChange();
                    });
                }

                Log.d("TAG",
                        String.format("onComponentChange key:%s, oldComponent:%s, newComponent:%s",
                                componentKey,
                                oldComponent,
                                newComponent));

            }

            @Override
            public void onInitProcess(DJISDKInitEvent djisdkInitEvent, int i) {

            }

            @Override
            public void onDatabaseDownloadProgress(long l, long l1) {

            }

        };
        DJISDKManager.getInstance().registerApp(application.getApplicationContext(), mDJISDKManagerCallback);
        Toast.makeText(application.getApplicationContext(), "registering, pls wait...", Toast.LENGTH_LONG).show();
    }

    private void notifyStatusChange() {
        mHandler.removeCallbacks(updateRunnable);
        mHandler.postDelayed(updateRunnable, 500);
    }

    private final Runnable updateRunnable = new Runnable() {
        @Override
        public void run() {
            Intent intent = new Intent(FLAG_CONNECTION_CHANGE);
            application.getApplicationContext().sendBroadcast(intent);
        }
    };

}